package com.egao.common.component.wechat;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.egao.common.core.Constants;
import com.egao.common.core.log.LogWechat;
import com.egao.common.core.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;


/**
 * 学校企业号工具类
 * @author lym
 */
@Slf4j
@Component
public class WeChatUtils {

    /** 移动校园网 */
    private final static String YDDM = "https://wx2.zuel.edu.cn";
    private final static String APP_ID = "200200424131910103";
    private final static String APP_SECRET = "3pi8gct86mnrm306rnloean51mhoeh8h";
    private final static String WID = "3";
    /** 成功状态值 */
    private final static String SUCCESS = "0";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static StringRedisTemplate redisTemplate;

    @PostConstruct
    public void getRedisTemplate() {
        redisTemplate = stringRedisTemplate;
    }

    /**
     * 获取token
     * 120分钟access_token失效
     * @return JsonResult
     */
    public static JsonResult getAccessToken() {
        // 获取企业微信accessToken
        String accessTokenCache = redisTemplate.opsForValue().get("work:wechat:token");
        if (!StrUtil.isBlank(accessTokenCache)) {
            return JsonResult.ok("获取缓存成功").setData(accessTokenCache);
        }

        // accessToken过期重新获取
        String url = YDDM + "/api/third/get-token?appid=" + APP_ID + "&appsecret=" + APP_SECRET;
        String result = HttpRequest.get(url).execute().body();
        JSONObject jsonObj = JSON.parseObject(result);
        String e = jsonObj.getString("e");
        String m = jsonObj.getString("m");
        String d = jsonObj.getString("d");
        if (!SUCCESS.equals(e)) {
            LogWechat.error("企业微信AccessToken查询失败:" + m);
            return JsonResult.error(m);
        }

        JSONObject dObj = JSON.parseObject(d);
        String accessToken = dObj.getString("access_token");
        if (StrUtil.isBlank(accessToken)) {
            LogWechat.error("企业微信AccessToken查询成功但值为空");
            return JsonResult.error("未获取到token");
        }
        // 缓存有效期50分钟
        redisTemplate.opsForValue().set("work:wechat:token", accessToken, 50, TimeUnit.MINUTES);
        LogWechat.error("企业微信AccessToken查询完成");
        return JsonResult.ok("查询缓存成功").setData(accessToken);
    }

    /**
     * 获取学生信息
     *
     * @param code 企业微信code
     * @return JsonResult
     */
    public static String getStudent(String code) {
        JsonResult ajaxJson = getAccessToken();
        if (ajaxJson.getCode() == Constants.RESULT_ERROR_CODE) {
            LogWechat.error("企业微信获取AccessToken失败: " + ajaxJson.getMsg());
            return "";
        }
        String accessToken = ajaxJson.getData().toString();

        try {
            String url = YDDM + "/uc/api/oauth/user-by-code?code=" + code + "&access_token=" + accessToken;
            String result = HttpRequest.get(url).execute().body();
            JSONObject jsonObj = JSON.parseObject(result);
            String e = jsonObj.getString("e");
            String m = jsonObj.getString("m");
            String d = jsonObj.getString("d");
            if (SUCCESS.equals(e)) {
                LogWechat.info("登陆人信息:" + result);

                JSONObject dObj = JSON.parseObject(d);
                String roleResult = dObj.getString("role");
                JSONObject roleObj = JSON.parseObject(roleResult);
                String number = roleObj.getString("number");
                return number;
            } else {
                LogWechat.error("根据CODE未查询到用户信息: " + result);
            }
            return "";
        } catch (Exception ex) {
            LogWechat.error("企业微信获取学生失败: " + ex.getMessage());
            return "";
        }
    }

    public static JsonResult push(String[] students, String content) {
        JsonResult jsonResult = pushData(students, content);
        if (jsonResult.getCode() == 0) {
            String url = YDDM + "/uc/api/ucs/qywx";
            String params = (String) jsonResult.getData();
            String result = HttpRequest.post(url).header("Content-Type", "application/x-www-form-urlencoded").body(params).execute().body();

            // 结果处理
            JSONObject jsonObj = JSON.parseObject(result);
            String e = jsonObj.getString("e");
            if ("0".equals(e)) {
                return JsonResult.ok().setData(result).put("params", params);
            } else if ("60005".equals(e)) {
                // 删除缓存
                redisTemplate.delete("work:wechat:token");

                push(students, content);
            }
            return JsonResult.ok().setData(result).put("params", params);
        }
        return jsonResult;
    }

    /**
     * 构建企业推送需要的参数
     *
     * @param xh 学号集合
     * @return
     */
    public static JsonResult pushData(String[] xh, String content) {
        JsonResult ajaxJson = getAccessToken();
        if (ajaxJson.getCode() == Constants.RESULT_ERROR_CODE) {
            LogWechat.error("企业微信获取AccessToken失败: " + ajaxJson.getMsg());
            return ajaxJson;
        }
        String accessToken = ajaxJson.getData().toString();

        StringBuilder url = new StringBuilder("access_token=" + accessToken);
        for (int i = 0; i < xh.length; i++) {
            url.append("&numbers[").append(i).append("]=").append(xh[i]);
        }
        url.append("&content[msgtype]=text");
        url.append("&content[text][content]=").append(content);
        url.append("&wid=" + WID);
        return JsonResult.ok().setData(url.toString());
    }

}
